//
//  CPPictureView.swift
//  weibo
//
//  Created by zcp on 16/5/17.
//  Copyright © 2016年 zcp. All rights reserved.
//

import UIKit



/// 最大列数
private let MaxColumn:CGFloat = 3

///图片间间隔
private var imageViewMargin: CGFloat = 4

///图片宽和高
private var imageViewWH:CGFloat = (UIScreen.mainScreen().bounds.width - 2*cellMargin - (MaxColumn - 1)*imageViewMargin)/MaxColumn

class CPPictureView: UIView {
///图片的url数组
    var pictureUrls: [NSURL]? {
        didSet{
        
            let size = layout(pictureUrls)
            
            self.snp_updateConstraints { (make) -> Void in
                make.size.equalTo(size)
            }
        }
    }
    override init(frame: CGRect) {
        super.init(frame: frame)
        backgroundColor = UIColor.yellowColor()
        prepareUI()

    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }


///MARK: - 布局子控件pictureUrls: [NSURL]?
    private func layout(pictureUrls: [NSURL]?) -> CGSize{
    
        //要显示图片数量
        let count = pictureUrls?.count ?? 0
        //列数
        var column = 3
        //判断要显示几列
        if count == 1
        {
            column = 1
        }
        else if count == 2 || count == 4
        {
            column = 2
        }
        var index = 0
        for imageView in imageViews
        {
            if index >= count
            {
                //隐藏
                imageView.hidden = true
            }
            else
            {
                //显示布局
                imageView.hidden = false
                let x = CGFloat((index % column))*(imageViewMargin + imageViewWH)
                let y = CGFloat((index / column))*(imageViewMargin + imageViewWH)
                imageView.frame = CGRect(x: x, y: y, width: imageViewWH, height: imageViewWH)
                //赋值
                let url = pictureUrls![index]
                
                
                imageView.sd_setImageWithURL(url)
            
                
            }
            index++
        }
        //计算配图的大小
        if count == 0 {
        
            return CGSizeZero
        }
        //行数
        let row = (count + column - 1) / column
        let width = imageViewWH * CGFloat(column) + imageViewMargin * CGFloat(column-1)
        let height = imageViewWH * CGFloat(row) + imageViewMargin * CGFloat(row-1)
        return CGSize(width: width, height: height)
     
    }
///图片数组
    private var imageViews = [UIImageView]()

//MARK: - 添加控件
private func prepareUI(){
    
    for _ in 0..<9
    {
        let imageView = UIImageView()
//        imageView.backgroundColor = UIColor.greenColor()
        imageView.contentMode = UIViewContentMode.ScaleAspectFill
        imageView.clipsToBounds = true
        self.addSubview(imageView)
        imageViews.append(imageView)
    }
    
    }
}
